<template>
  <div id="newsBox">
    <!-- 新闻头部 -->
    <news-header
      @openNewsTypeDialogBtnClick="openNewsTypeDialogBtnClick"
      @changeNewsHeaderData="headerSearchBtnClick"
    />
    <!-- 新闻表格 -->
    <news-table
      :tableLoadingStatus="tableLoadingStatus"
      :newsTableData="newsTableData"
      :isNewsStatusDisabled="isNewsStatusDisabled"
      @newsStatusChangeEvent="newsStatusChangeEvent"
      @deleteNewsLinkClick="deleteNewsLinkClick"
      @filterChange="tableFilterChange"
      @firstPageClick="firstPageClick"
      @previousPageClick="previousPageClick"
      @nextPageClick="nextPageClick"
      @lastPageClick="lastPageClick"
      @junkToOtherPage="junkToOtherPage"
    />

    <!-- 新闻类型 -->
    <el-dialog
      title="新闻类型"
      :visible.sync="isShowNewsTypeDialog"
      width="681px"
      class="dialogTitle_G"
      @close="newsTypeDialogClose"
    >
      <el-dialog
        width="30%"
        title="添加新闻类型"
        :visible.sync="innerVisible"
        append-to-body
        :close-on-click-modal="false"
        @close="newsTypeInnerDialogClose"
      >
        <el-form
          :model="innerDialogForm"
          :rules="rules"
          :validate-on-rule-change="false"
          ref="innerDialog"
        >
          <el-form-item label="新闻类型" prop="newsType">
            <el-input
              placeholder="请输入新闻类型"
              v-model="innerDialogForm.newsType"
            ></el-input>
          </el-form-item>
        </el-form>

        <div class="dialog-footer_G">
          <cs-btn
            type="primary"
            @click.native="addNewsTypeConfirmBtnClick('innerDialog')"
            btnText="确定"
            :buttonStatus="addNewsTypebtnStatus"
            class="confirmBtn"
          />
          <cs-btn @click.native="innerVisible = false" btnText="取消" />
        </div>
      </el-dialog>
      <div>
        <cs-tag
          type="plainPrimary"
          v-for="item in newsTypeData"
          :key="item.id"
          @closeTagEvent="closeTagEvent(item.id)"
          >{{ item.label }}</cs-tag
        >
        <cs-btn
          btnText="添加新闻类型"
          type="primary"
          @click.native="innerVisible = true"
        />
      </div>
      <div class="dialog-footer_G">
        <cs-btn
          type="primary"
          @click.native="isShowNewsTypeDialog = false"
          btnText="确定"
          class="confirmBtn"
        />
        <cs-btn @click.native="isShowNewsTypeDialog = false" btnText="取消" />
      </div>
    </el-dialog>

    <!-- 删除新闻对话框 -->
    <el-dialog
      title="删除新闻"
      :visible.sync="isShowDeleteDialog"
      width="681px"
      class="dialogTitle_G"
      @close="closeDelNewsDialog"
    >
      <div class="deleteTip1_G" v-html="msg1 + this.currentSelect + msg2"></div>
      <div class="deleteTip2_G">确定<b>删除</b>选中的新闻？</div>
      <div class="dialog-footer_G">
        <cs-btn
          type="primary"
          @click.native="confirmDeleteNewsBtnClick"
          btnText="确定"
          :buttonStatus="delNewsBtnStatus"
        />
        <cs-btn @click.native="isShowDeleteDialog = false" btnText="取消" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import NewsHeader from "./cpns/NewsHeader.vue";
import NewsTable from "./cpns/NewsTable.vue";
import CsBtn from "@/components/CsBtn/CsBtn.vue";
import CsTag from "@/components/CsTag/CsTag.vue";

import { mapState } from "vuex";

import {
  getNewsList,
  changeNewsStatus,
  createNewsType,
  deleteNewsType,
  deleteNews,
} from "@/api/news";

export default {
  name: "news",
  components: {
    NewsHeader,
    NewsTable,
    CsBtn,
    CsTag,
  },
  data() {
    return {
      // 头部数据
      headerData: "",
      // 表格数据
      newsTableData: {},
      // 新闻表格查询接口参数
      tabelParams: {
        offset: 1,
        limit: 10,
        keyword: "",
        fromTime: "",
        toTime: "",
        categoryIds: [],
        status: [],
      },
      tableLoadingStatus: false,
      // 是否禁用表格状态switch
      isNewsStatusDisabled: false,
      // 新闻类型对话框 start
      isShowNewsTypeDialog: false,
      addNewsTypebtnStatus: false,
      innerVisible: false,
      innerDialogForm: {
        newsType: "",
      },
      rules: {
        newsType: [
          { required: true, message: "请输入新闻类型", trigger: "blur" },
        ],
      },
      // 新闻类型对话框end
      // 删除新闻对话框数据 start
      isShowDeleteDialog: false,
      currentSelect: 1,
      msg1: "您已选择<b>",
      msg2: "个</b>新闻",
      deleteId: [],
      delNewsBtnStatus: false,
      // 删除新闻对话框数据 end
    };
  },
  created() {
    this.getNewsTableData();
    this.getAllNewsList();
  },
  computed: {
    ...mapState("news", ["newsTypeData"]),
  },
  methods: {
    async getAllNewsList() {
      await this.$store.dispatch("news/getAllNewsType");
    },
    // 头部搜索搜索按钮点击事件
    headerSearchBtnClick(headerData) {
      this.headerData = headerData;
      this.updateTable();
    },

    // 获取新闻列表
    async getNewsTableData() {
      this.tableLoadingStatus = true;
      const data = await getNewsList(this.tabelParams);
      console.log(data);
      if (data.code === 0 && data.data) {
        this.newsTableData = {};
        this.newsTableData.list = [];
        const tableData = data.data;
        this.newsTableData.currentPage = tableData.currPage;
        this.newsTableData.pageSize = tableData.pageSize;
        this.newsTableData.totalCount = tableData.totalCount;
        this.newsTableData.totalPage = tableData.totalPage;

        tableData.list.forEach((item) => {
          this.newsTableData.list.push({
            id: item.id,
            firstTitle: item.firstTitle,
            categories: item.categories,
            publisher: item.createBy.username,
            views: item.visitNumber,
            publishTime: item.createTime,
            status: item.status,
          });
        });
      }
      this.tableLoadingStatus = false;
    },

    // 更新表格
    updateTable() {
      this.tabelParams.keyword = this.headerData.newsTitle;
      this.tabelParams.fromTime = this.headerData.timeValue
        ? this.headerData.timeValue[0]
        : "";
      this.tabelParams.toTime = this.headerData.timeValue
        ? this.headerData.timeValue[1]
        : "";
      this.getNewsTableData();
    },
    // 表格筛选添加改变
    tableFilterChange(filters) {
      console.log(filters);
      if (filters.newsType) {
        this.tabelParams.categoryIds = filters.newsType;
      } else if (filters.status) {
        this.tabelParams.status = filters.status;
      }
      this.getNewsTableData();
    },

    // 第一页按钮点击
    firstPageClick() {
      this.tabelParams.offset = 1;
      this.getNewsTableData();
    },
    // 上一页按钮点击
    previousPageClick() {
      this.tabelParams.offset -= 1;
      this.getNewsTableData();
    },
    // 下一页按钮点击
    nextPageClick() {
      this.tabelParams.offset += 1;
      this.getNewsTableData();
    },
    // 最后一页按钮点击
    lastPageClick() {
      this.tabelParams.offset = this.newsTableData.totalPage;
      this.getNewsTableData();
    },
    // 输入页数跳转
    junkToOtherPage(pageNum) {
      this.tabelParams.offset = pageNum;
      this.getNewsTableData();
    },
    // 改变新闻状态
    async newsStatusChangeEvent(status, id) {
      // 禁用切换按钮
      this.isNewsStatusDisabled = true;
      const data = await changeNewsStatus({
        newsDetailId: id,
        status,
      });
      if (data.code === 0) {
        this.$message({
          message: "改变新闻状态成功",
          type: "success",
        });
        this.getNewsTableData();
        // 解禁切换按钮
        this.isNewsStatusDisabled = false;
      } else {
        // 解禁切换按钮
        this.isNewsStatusDisabled = false;
      }
    },
    // 确定删除新闻事件
    async confirmDeleteNewsBtnClick() {
      this.delNewsBtnStatus = true;
      const data = await deleteNews({ newsDetailIds: this.deleteId });
      console.log(data);
      if (data.code === 0) {
        this.$message({
          message: "删除新闻成功",
          type: "success",
        });
        this.getNewsTableData();
        this.isShowDeleteDialog = false;
      } else {
        this.$message.error("删除新闻失败");
      }
      this.delNewsBtnStatus = false;
    },
    // 删除新闻对话框关闭事件
    closeDelNewsDialog() {
      this.deleteId = [];
    },
    // 打开新闻类型对话框事件
    openNewsTypeDialogBtnClick() {
      this.isShowNewsTypeDialog = true;
    },
    // 新增新闻类型确认按钮
    addNewsTypeConfirmBtnClick(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.addNewsTypebtnStatus = true;
          const data = await createNewsType({
            label: this.innerDialogForm.newsType,
          });
          if (data.code === 0) {
            await this.getAllNewsList();
            this.$message({
              message: "添加新闻类型成功",
              type: "success",
            });
            this.innerVisible = false;
          }
          this.addNewsTypebtnStatus = false;
        }
      });
    },
    // 关闭标签事件
    closeTagEvent(id) {
      this.$confirm("此操作将永久删除该类型, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        closeOnClickModal: false,
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            const data = await deleteNewsType({ newCategoryIds: id });
            if (data.code === 0) {
              await this.getAllNewsList();
              done();
              setTimeout(() => {
                instance.confirmButtonLoading = false;
              }, 300);
            }
          } else {
            done();
          }
        },
      })
        .then(async () => {
          this.$message({
            type: "success",
            message: "删除新闻类型成功!",
          });
        })
        .catch(() => {});
    },
    // 新闻类型内部对话框关闭事件
    newsTypeInnerDialogClose() {
      this.$refs.innerDialog.resetFields();
    },
    // 新闻类型对话框关闭事件
    newsTypeDialogClose() {
      this.isShowNewsTypeDialog = false;
    },
    // 删除表格链接点击事件
    deleteNewsLinkClick(id) {
      this.deleteId = [id];
      this.isShowDeleteDialog = true;
    },
  },
};
</script>

<style lang="scss" scoped>
#newsBox {
  margin: 26px;
}

// 新闻类型对话框样式 start
.cs-tag {
  margin-right: 29px;
  margin-bottom: 35px;
}

.confirmBtn {
  margin-top: 11px;
}
// 新闻类型对话框样式 end
</style>
